const util = require('../../utils/util.js');
const api = require('../../config/api.js');

//获取应用实例
const app = getApp();
import Toast from '../../lib/vant-weapp/toast/toast'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    deliveryNotes:"",//送货备注
    milk:"", // 送牛奶
    notes:"",//备注
    deposit:"",//押金
    username:'姓名',// 姓名
    phone:'15093631865',// 手机
    address:"dsfasdfasdfsd",//地址
    landline:"",//座机
    email:"12267792",//email
    errorAddress:"", // 地址不能为空
    errorUsername:"", // 姓名不能为空
    errorPhone:"", // 手机号格式错误
    id:"",
    msId:"87"
  },
  handleFieldChange(e) {
    // 获取是哪个van-field的回调
    let fieldName = e.currentTarget.dataset.name
    // 获取输入框的新值
    let newValue = e.detail
    // 定义好要更新的data对象，
    let data = {}
    // 利用JS的对象的键名支持字符串形式的下标，自动给每个字段去更新，不用手写
    data[fieldName] = newValue.value
    this.setData(data)
},
  TakePhoneFn(event){
    var Mob = /^1[3,4,5,6,7,8,9]\d{9}$/;
    if (!Mob.test(event.detail.value)) {
      this.setData({errorPhone : "手机号码格式不正确"})
    }else{
      this.setData({errorPhone : "",phone:event.detail.value})
    }
},
addGotoUrlFn(){
  var that = this
  setTimeout(function(){
     that.addGotoUrl()
  })
},
  addGotoUrl(){
    if(this.data.username === ''){
      this.setData({errorUsername : "姓名不能为空"})
      return
    }
    if(this.data.phone === ''){
      this.setData({errorPhone : "手机号格式错误"})
      return
    }
    if(this.data.address === ''){
      this.setData({errorAddress : "地址不能为空"})
      return
    }
    var data = {
        msId:this.data.msId,
        name:this.data.username,
        mobileNumber:this.data.phone,
        email:this.data.email,
        address:this.data.address
    }
    var url = api.createUrl
    var test ="添加成功"
    if(this.data.id){
      url = api.editUrl
      data.id = this.data.id
      test ="修改成功"
    }
    util.request(url,data,"POST").then(function(res) {
      console.log(res)
      if (res.errno === 0) {
        Toast.success(test);
      }
    });
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    prevPage.setData({
      pages: '1',
      hotGoods:[]
    });
    prevPage.getlistUrl()
    wx.navigateBack({
      delta: 1,
    })
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    if(options.id){
        this.setData({
          id: options.id,
          msId: options.msid,
          username: options.name,
          phone: options.phone,
          email: options.email,
          address: options.address
        });
        console.log(this.data.msId)
    }
  }
})